package day11.CRUD;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.ResultSet;

public class Demo4 {
    /**
     * 获取自动生成的主键
     */
    public static void main(String[] args) {

        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            String sql = "insert into test1(name) values(?)";
            st = (PreparedStatement) conn.prepareStatement(sql);
            st.setString(1, "aaa");//在插入name时数据库会自动生成id
            st.executeUpdate();

            rs = st.getGeneratedKeys();//获取生成的主键
            if (rs.next()) {
                System.out.println(rs.getInt(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.release(conn, st, rs);
        }
    }
}
